import { ref, getCurrentInstance, onMounted } from 'vue'
import { Query } from '@/hook/mapgis-api/Query'
import { Point } from '@/hook/mapgis-api/Point'
import { docLayer } from '@/hook/LoadBasicMap/index'
import { storeToRefs } from 'pinia'
import { useCommonStore } from '@/stores/common'
/* 引入公共状态管理对象 */
const store = useCommonStore()
const { changeEventFlag } = storeToRefs(store)
export const useChangeEventHook = () => {
  const { proxy } = getCurrentInstance()
  const popupContent = ref([])
  let popup = null
  let $map = null
  let id = null
  let color = 6
  onMounted(() => {
    $map = proxy.$map
    var container = document.getElementById('popup')
    popup = new ol.Overlay({
      //要转换成overlay的HTML元素
      element: container,
      //当前窗口可见
      autoPan: true,
      //Popup放置的位置
      positioning: 'bottom-center',
      //是否应该停止事件传播到地图窗口
      stopEvent: true,
      autoPanAnimation: {
        //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
        duration: 250
      }
    })
    $map.addOverlay(popup)
    $map.on('click', (e) => {
      if (!changeEventFlag.value) {
        return
      }
      let position = e.coordinate
      let service = {
        name: import.meta.env.VITE_DOC_NAME,
        layerId: 2
      }
      Query.queryByPnt({
        position,
        service,
        success: (feature) => {
          if (!feature) {
            return
          }
          id = feature[0].id_
          popupContent.value = feature[0].values_.values_
          let position = feature[0].getGeometry().getCoordinates()[0]
          popup.setPosition(position)
        }
      })
    })
  })
  const closePopup = () => {
    //未定义popup位置
    popup.setPosition(undefined)
    return false
  }
  const changeEvent = () => {
    let position = popup.getPosition()
    // //   将数组转化成对象
    let attr = [
      { name: '事件编号', type: 'string', value: popupContent.value.事件编号 },
      { name: '事件类型', type: 'string', value: popupContent.value.事件类型 },
      { name: '事件等级', type: 'string', value: popupContent.value.事件等级 },
      { name: '发生时间', type: 'string', value: popupContent.value.发生时间 },
      { name: '发生地点', type: 'string', value: popupContent.value.发生地点 },
      { name: '车牌号', type: 'string', value: popupContent.value.车牌号 },
      { name: '驾驶员', type: 'string', value: popupContent.value.驾驶员 },
      { name: '处理状态', type: 'string', value: popupContent.value.处理状态 }
    ]
    let service = {
      name: import.meta.env.VITE_DOC_NAME,
      layerId: 2
    }
    if (popupContent.value.处理状态=== '0'){
      color = 6
    }else if (popupContent.value.处理状态=== '1'){
      color = 4
    }else if (popupContent.value.处理状态=== '2'){
      color = 7
    }
    Point.update({
      position,
      attr,
      service,
      docLayer,
      color,
      id
    })
    
    popup.setPosition(undefined)
  }

  return { popupContent, closePopup, changeEvent }
}
